<template>
    <div class="distributionAdd">
        <van-nav-bar title="新增分发" left-text="返回" left-arrow @click-left="onClickLeft" @click-right="onClickRight">
        </van-nav-bar>
        <van-form @submit="onSubmit" @failed="onFailed" ref="vanFormRef">
         
            <van-cell-group inset>
                <van-field v-if="!isAdmin" @click="showWritePopup" class="groupField" v-model="imgSrc"
                    required name="imgSrc" label="签名：" :rules="[{ required: true, message: '请填写签名' }]">
                    <template #input>
                        <img v-if="imgSrc" :src="imgSrc"
                            style="width: 100%;height: 150px;">
                        <!-- <span style="padding: 20px;" @click="showWritePopup">
                                <van-icon name="add" size="30" />
                            </span> -->
                    </template>
                </van-field>
                <van-cell-group v-if="isAdmin">
                    <van-field v-model="formState.content" required label="分发内容：" type="textarea" placeholder="请输入分发内容"
                        rows="5" autosize :rules="[{ required: true, message: '请输入分发内容' }]" />
                </van-cell-group>
                <van-cell-group>
                    <van-field @click="openPopup" required readonly type="textarea" v-model="formState.activeName"
                        autosize label="分发人:" placeholder="请选择分发人" :rules="[{ required: true, message: '请选择分发人' }]" />
                </van-cell-group>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    提交
                </van-button>
            </div>
        </van-form>
    </div>
    <van-popup v-model:show="showPopup" position="bottom">
        <van-tree-select text-key="name" :items="treeItems" :main-active-index.sync="mainActiveIndex"
            :active-id.sync="activeId" @click-nav="onNavClick" @click-item="onItemClick" />
    </van-popup>
    <van-popup v-model:show="showWrite">
        <div style="width: 90vw; height: 80vh;position: relative;overflow: hidden;">
            <VueSignaturePad ref="signaturePad" class="signature" :options="options" width="100%" height="100%">
            </VueSignaturePad>
            <div
                style="display: flex; transform: rotate(90deg); gap: 10px;bottom: 100px;left: -50px; position: absolute;">
                <van-button type="danger" @click="closeSign">关闭</van-button>
                <van-button type="warning" @click="clearSign">清屏</van-button>
                <van-button type="primary" @click="saveUploadSign">确认</van-button>
            </div>
        </div>
    </van-popup>
</template>
<script setup>
import { onMounted, ref, nextTick } from "vue";
import { useRouter,useRoute } from "vue-router";
import { Toast, Dialog } from "vant";
import DistributionInfoApi from '../api/distribution'
import { parseTime, base64ToFile, debounce } from "../../../utils";
import { VueSignaturePad } from 'vue-signature-pad';
import store from "../../../store";
import {
    getToken,
} from "../../../utils/auth";
import _ from "lodash";
import axios from "axios";
const router = useRouter();
const route = useRoute();
const isAdmin = store.getters.roles.includes('super_admin') && !route.query.isRoot
const signaturePad = ref(null)

const formState = ref({
    secureWrite: "",
    receiverIds: [],
    content: "",
    activeName: ""
})
const imgSrc=ref()
const options = ref({
    penColor: '#000000',
    minWidth: 2,
    maxWidth: 2,
    backgroundColor: "rgba(255, 255, 255)",
});
const showWrite = ref(false)
const showPopup = ref(false)
const treeItems = ref()
const activeId = ref([])
const activeName = ref([])
const mainActiveIndex = ref(0)
onMounted(() => {
   
    getPerson()
})
const getPerson = () => {
    DistributionInfoApi.getPeerAndSubDeptsWithUsers().then(res => {
        treeItems.value = [...res.data.data.peerDepartments, ...res.data.data.subDepartments]
        addTextToTree(treeItems.value)
    })
}
const onClickLeft = () => router.push('/main');
const onClickRight = () => router.push('/recordsInfo/add');
const onNavClick = function (index) {
    mainActiveIndex.value = index;
}
const onItemClick = function (data) {

    const index = activeId.value.indexOf(data.id); // 检查 ID 是否已存在在数组中
    if (index > -1) { // 如果已存在，则移除该 ID
        activeId.value.splice(index, 1);
        activeName.value.splice(index, 1)
    } else { // 如果不存在，则添加该 ID 到数组中
        activeName.value.push(data.roleName?`${data.name}(${data.roleName})`:data.name)
        activeId.value.push(data.id);
    }

    activeName.value.length > 0 ? formState.value.activeName = activeName.value.join(",") : null
    formState.value.receiverIds = activeId.value
}
const clearSign = () => {
    signaturePad.value.clearSignature();
};
const openPopup = () => {
    showPopup.value = true
}
const closeSign = () => {
    signaturePad.value.clearSignature();
    formState.value.secureWrite = ""
    imgSrc.value=""
    showWrite.value = false
}
async function uploadFile(files) {
    return new Promise(async (resolve, reject) => {
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append('file', files[i]); // 添加每个文件到 FormData 中
        }

        try {
            const response = await axios.post(import.meta.env.VITE_APP_BASE_API + '/file/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    "Authorization": getToken()
                }
            });

            resolve(response.data.data)
        } catch (error) {
            console.error('文件上传失败:', error);
        }
    })

}
const changImg = (base64Image) => {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = base64Image;
        img.onload = function () {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            // 旋转 90 度，交换宽高
            canvas.width = img.height;
            canvas.height = img.width;

            // 移动原点到左下角
            ctx.translate(0, canvas.height);
            // 逆时针旋转 90 度，使用负角度
            ctx.rotate(-Math.PI / 2);

            // 绘制图片
            ctx.drawImage(img, 0, 0);

            // 获取旋转后的 Base64 数据
            const rotatedBase64 = canvas.toDataURL('image/png');
            resolve(rotatedBase64)
        }
    })

}
const saveUploadSign = () => {
    nextTick(async () => {
        const { isEmpty, data } = signaturePad.value.saveSignature();
        if (isEmpty) return;
        showWrite.value = false
        signaturePad.value.clearSignature();
        imgSrc.value= await changImg(data)
        let qians = await uploadFile([base64ToFile(imgSrc.value, "qianming.png")])
        formState.value.secureWrite = qians.fileId
    })

}
const showWritePopup = () => {
    showWrite.value = true;
    nextTick(() => {
        signaturePad.value.clearSignature();
    }, 0)
}
function addTextToTree(nodes) {
    nodes.forEach(node => {
        node.text = node.roleName?`${node.name}(${node.roleName})`:node.name; // 添加 text 字段，其值与 name 相同
        if (node.children && node.children.length > 0) {
            addTextToTree(node.children); // 递归处理子节点
        }
    });
}
// 表单提交
const onSubmit = debounce(() => {
    handleAdd()
}, 1000)

const onFailed = (errorInfo) => {
    Toast.fail('提交失败')
}
const handleAdd = async () => {
    return new Promise(async (resolve, reject) => {
        if (isAdmin) {
            DistributionInfoApi.add({ ...formState.value }).then(res => {
                if (res.data.code == 200) {
                    Toast.success("添加成功")
                    router.push("/distribution")
                } else {
                    Toast.success("添加失败")
                }
            })
        } else {
           DistributionInfoApi.receiveFile({fileId:formState.value.secureWrite,distributionId:route.query.distributionId,nodeId:route.query.nodeId}).then(res=>{
              if(res.data.code==200){
                DistributionInfoApi.add({mainRecordId:route.query.distributionId,receiverIds:formState.value.receiverIds}).then(response=>{
                if(response.data.code==200){
                   Toast.success("签收成功")
                   router.push("/distribution")
                }else{
                    Toast.fail("签收失败")
                }
              }).catch(error=>{
                console.log(error)
              })
              }else{
                  Toast.fail(res.data.message)
              }
             
           }).catch(error=>{
              console.log(error)
           })
        }

    })
}
</script>